<template>
  <div class="wrap">
    <div class="level-box">
      <img src="/static/di.png" alt="">
      <div class="current-level">{{subject.cardNumber}}</div>
      <img src="/static/guan.png" alt="">
      <div class="energy-box">
        <img src="/static/energy.png" alt=""> {{energy}}
      </div>
    </div>
    <!-- 题目展示区域 -->
    <div class="question-title" :class="{word:qType==3}" :data-title="subject.title">
      <div class="title-box">
        {{subject.title}}
      </div>
    </div>
    <!-- 图片提示 -->
    <div v-if="qType==1" class="question-img">
      <img :src="IMGHEAD+subject.image" :style="imgSize" alt="" @load="imgLoaded">
    </div>
    <!-- 音频提示 -->
    <questionAudio v-if="qType==2" :audioSrc="subject.audio" :isStop="isStop"></questionAudio>
    <!-- 功能操作区域 -->
    <div v-if="qType!=3" class="fn-box">
      <div class="fn-btn idea-m" @click="tip()">
        <!-- <div class="sub-animate" :class="{flyUp:isFly}"> -->
          <!-- <img src="/static/energy.png" alt=""> -{{tipCost}} -->
        <!-- </div> -->
        <img src="/static/tip.png" alt="">
        <span>提示</span>
      </div>
      <div class="fn-btn skip-m" @click="skip()">
        <img src="/static/skip.png" alt="">
        <span>跳过</span>
      </div>
      <div class="fn-btn user-m">
          <!-- 金幣不足彈窗 -->
        <outEnergy v-if="isEnergyBox" @leftClick="addEnergyByPay()" @close="closeEnergy()" type="energy"></outEnergy>
        <button plain="true" open-type="share">
          <img src="/static/help.png" alt="">
          <span>求助</span>
        </button>
      </div>

    </div>
    <!-- 填字 -->
    <fillWord v-if="subject&&sType==2" :subject="subject" :isTip="isTip" @getSuccess="successHandle" @getFail="failHandel"></fillWord>
    <!-- 选项 -->
    <selectOption v-if="subject&&sType==1" :subject="subject" :isTip="isTip" :qType="qType" @getSuccess="successHandle" @isPass="isPass=true" @getFail="failHandel" @outEnergy="isEnergyBox = true "></selectOption>
    <!-- 答题成功好友弹窗 -->
    <overFriendBox v-if="showOverFriendBox" type='over' :list="rankList" @close="closeFriendBox" :nextFriend="nextFriend"></overFriendBox>
    <!-- 好友帮助通知 -->
    <shareAnswerBox v-if="isShareAnswerBox" :user="shareUser" :type="resultType" @rightClick="closeBox" @close="closeBox" :card="shareUser.cardNumber"></shareAnswerBox>

    <!-- 功能操作区域 -->
    <!-- <div v-if="qType==3" class="fn-box mt34">
      <img src="/static/tip.png" alt="" @click="tip()">
      <img src="/static/skip.png" alt="" @click="skip()">
      <button plain="true" open-type="share">
        <img src="/static/help.png" alt="">
      </button>
    </div>
     -->

    <div v-if="qType==3" class="fn-box mt34">
      <div class="fn-btn idea-m" @click="tip()">
        <div class="sub-animate" :class="{flyUp:isFly}">
          <img src="/static/energy.png" alt=""> -{{tipCost}}
        </div>
        <img src="/static/tip.png" alt="">
        <span>提示</span>
      </div>
      <div class="fn-btn skip-m" @click="skip()">
        <img src="/static/skip.png" alt="">
        <span>跳过</span>
      </div>
      <div class="fn-btn user-m">
        <!-- 金幣不足彈窗 -->
        <outEnergy v-if="isEnergyBox" @leftClick="addEnergyByPay()" @close="closeEnergy()" type="energy"></outEnergy>
        <button plain="true" open-type="share">
          <img src="/static/help.png" alt="">
          <span>求助</span>
        </button>
      </div>
    </div>
    <!-- 答对弹窗 -->
    <passCardBox v-if="isShowQuestionBox&&questionBoxConfig.type" :config="questionBoxConfig" @leftClick="unLike()" @rightClick="like()" @center="nextCard()"></passCardBox>
    <!-- 跳过弹窗 -->
    <skipCardBox v-if="isShowSkipBox" @leftClick="noSkip()" @rightClick="yesSkip()" @close="closeSkip()" type="skip"></skipCardBox>
    <!-- <skipCardBox v-if="isEnergyBox" @leftClick="closeEnergy()" @rightClick="addEnergyByPay()" @close="closeEnergy()" type="energy"></skipCardBox> -->
    <passGame v-if="isPassGame" @centerClick="passGame()" @close="passGame()"></passGame>
    <!-- 帮助列表 -->
    <helpList :list="helpArry"></helpList>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import questionAudio from "./components/questionAudio";
import fillWord from "./components/fillWord";
import selectOption from "./components/selectOption";
import passGame from "@/components/passGame";
import { shareInfo } from "@/config/shareInfo";
import overFriendBox from "@/components/overFriendBox";
import helpList from "./components/helpList";
import shareAnswerBox from "@/components/shareAnswerBox";

const dataStack = []; //初始数据备份
export default {
  components: {
    questionAudio, //音频组件
    fillWord, //填字组件
    selectOption, //选项组件
    passGame,
    overFriendBox,
    helpList,
    shareAnswerBox
  },
  data() {
    return {
      shareInfo: shareInfo,
      imgSize: "",
      lastCard: false,
      isPassGame: false,
      isStop: false,
      isPass: false, //控制填字 提示 正确以后 不能在提示
      isTip: false, //提示开关
      isPaused: true, //光盘动画开关
      isTen: false,
      isExit: 1, //判断是否真退出或者10关自动退出
      isFly: false, //添加提示动画,
      tipCount: 0, //提示次数，每次退出或者更新题目
      subject: {}, //题目信息,
      qType: 0, //题目类型，1:图文，2：音文 3: 纯文字
      sType: 0, //选项类型 1：选项，2：选字
      rankList: [], //好友排行
      showOverFriendBox: false,
      nextFriend: false, //下一个好友
      answerCount: 0,
      questionBoxConfig: {}, //答案弹窗配置
      isShowQuestionBox: false,
      isShowSkipBox: false,
      isEnergyBox: false,
      auidioContext: null,
      helpArry: [], //帮助者列表
      isShareAnswerBox: false,
      resultType: "ten",
      shareUser: null
      // tipCost:0,//
    };
  },
  computed: {
    ...mapState([
      "IMGHEAD",
      "energy",
      "tipEnergy",
      "tipWordEnergy",
      "maxEnergy",
      "appInfo",
      "globalAudioContext",
      "sysConfig"
    ]),
    tipCost() {
      if (this.sType == 1) {
        return this.tipEnergy;
      } else {
        return this.tipWordEnergy;
      }
    }
  },
  methods: {
    ...mapMutations(["setEnergy","setCardNumber"]),
    imgLoaded(event) {
      let width = event.target.width,
        height = event.target.height;
      let nw, nh;
      if (height >= 424) {
        nh = 424;
        nw = width * (nh / height);
      } else {
        nw = 660;
        nh = height * (nw / width);
      }
      this.imgSize = `width:${nw}rpx;height:${nh}rpx;`;
    },
    initAudio() {
      this.auidioContext = wx.createInnerAudioContext();
      this.auidioContext.volume = 1;
      this.auidioContext.src = "static/audio/wrong.mp3";
    },
    playAudio(url) {
      this.auidioContext.src = url;
      this.auidioContext.play();
    },
    stopAudio() {
      this.auidioContext.stop();
    },
    getRankList() {
      this.fly.post("/getRankList").then(res => {
        let list = res.data.Result;
        this.rankList = [];
        for (let i = 0; i < list.length; i++) {
          if (
            list[i].cardNumber == this.subject.cardNumber &&
            list[i].userId != this.appInfo.userId
          ) {
            this.rankList.push(list[i]);
          } else if (list[i].cardNumber > this.subject.cardNumber) {
            this.nextFriend = list[i];
          } else {
            this.nextFriend = false;
          }
        }
      });
    },
    async getSubject() {
      //获取题目信息
      //初始化数据
      this.answerCount = 0;
      await this.fly
        .post("/getSubject", {
          userId: 0,
          subjectId: 0
        })
        .then(res => {
          this.tipCount = 0;
          this.isPass = false;
          this.subject = res.data.Result;
          if (this.helpArry.length > 0) {
            for (let i = 0; i < res.data.Result2.length; i++) {
              this.helpArry.push(res.data.Result2[i]);
            }
          } else {
            this.helpArry = res.data.Result2;
          }
          this.qType = res.data.Result.modeType;
          this.sType = res.data.Result.type;
          this.setEnergy(res.data.Result.strengthCount);
          this.setCardNumber(res.data.Result.cardNumber-1);
          this.getRankList();
          // 弹框配置
          this.questionBoxConfig = {
            type: res.data.Result.modeType,
            title: res.data.Result.answer,
            desc: res.data.Result.description,
            imgUrl: this.IMGHEAD + res.data.Result.image
          };
          // 背景音乐设置
          if (this.qType == 2) {
            this.globalAudioContext.stop();
            this.setGlobalAudioType("stop");
          } else if (this.setGlobalAudioType == "stop") {
            this.globalAudioContext.play();
            this.setGlobalAudioType("play");
          }
        });
    },

    tip() {
      // 先判断类型，在判断能量
      if (this.sType == 2) {
        if (this.energy >= this.tipWordEnergy) {
          this.isFly = true;
          setTimeout(() => {
            this.isFly = false;
          }, 1500);
          this.isTip = !this.isTip;
          this.tipCount++;
          this.setEnergy(this.energy - this.tipWordEnergy);
          wx.showToast({
            title: "金币-30",
            icon: "none",
            duration: 1000
          });
        } else {
          this.isEnergyBox = true;
        }
      } else {
        if (this.sType == 1 && this.energy >= this.tipEnergy) {
          if (!this.isPass) {
            this.isFly = true;
            setTimeout(() => {
              this.isFly = false;
            }, 100);
            this.isTip = !this.isTip;
            this.tipCount++;
          }
        } else {
          this.isEnergyBox = true;
        }
      }
    },
    skip() {
      this.isShowSkipBox = true;
    },
    noSkip() {
      this.isShowSkipBox = false;
    },
    yesSkip() {
      this.fly
        .post("/jumpSubject", {
          subjectId: this.subject.id,
          description: "跳关花费"
        })
        .then(res => {
          wx.requestPayment({
            timeStamp: res.data.Result.timeStamp,
            nonceStr: res.data.Result.nonceStr,
            package: res.data.Result.package,
            signType: res.data.Result.signType,
            paySign: res.data.Result.paySign,
            success: res => {
              this.isShowSkipBox = false;
              this.getSubject();
            }
          });
        });
    },
    closeEnergy() {
      this.isEnergyBox = false;
      // this.$router.back();
    },
    addEnergyByPay() {
      this.fly
        .post("/addStrength", {
          description: "回满体力"
        })
        .then(res => {
          wx.requestPayment({
            timeStamp: res.data.Result.timeStamp,
            nonceStr: res.data.Result.nonceStr,
            package: res.data.Result.package,
            signType: res.data.Result.signType,
            paySign: res.data.Result.paySign,
            success: res => {
              this.isEnergyBox = false;
              this.setEnergy(this.sysConfig.maxEnergy);
            }
          });
        });
    },
    closeSkip() {
      this.isShowSkipBox = false;
    },
    checkCardNumber() {
      if (this.subject.cardNumber % 10 == 0) {
        if (this.lastCard) {
          this.isPassGame = true;
        } else {
          // TODO  十关 弹窗
          this.$router.back(); //返回关卡页
        }
      } else {
        this.getSubject(); //获取新题目
      }
    },
    like() {
      //弹窗点击喜欢
      this.isShowQuestionBox = false;
      this.fly.post("/isLikeSubject", {
        subjectId: this.subject.id,
        type: 1
      });
      this.checkCardNumber();
    },
    unLike() {
      this.fly.post("/isLikeSubject", {
        subjectId: this.subject.id,
        type: 0
      });
      this.isShowQuestionBox = false;
      this.checkCardNumber();
    },
    nextCard() {
      this.getSubject(); //获取新题目
      this.isShowQuestionBox = false;
    },
    closeFriendBox() {
      this.isShowQuestionBox = true; //显示弹窗
      this.showOverFriendBox = false;
    },
    successHandle(answer) {
      // this.setEnergy(this.energy + 5);
      if (this.energy >= this.sysConfig.maxEnergy) {
        wx.showToast({
          title: "金币已达上限",
          icon: "none",
          duration: 1000
        });
      } else {
        wx.showToast({
          title: "金币+5",
          icon: "none",
          duration: 1000
        });
      }

      this.playAudio("static/audio/right.mp3");
      //回答正确
      this.answerCount++;
      if (this.sType == 2) {
        this.isPass = true;
      }
      this.fly
        .post("/submitSubject", {
          subjectId: this.subject.id,
          answer: answer,
          type: this.sType,
          promptCount: this.tipCount,
          replyCount: this.answerCount
        })
        .then(res => {
          if (res.data.Tag == 2) {
            this.lastCard = true;
            this.checkCardNumber();
          }
          if (this.subject.cardNumber % 10 == 0) {
            this.isExit = 0;
          } else {
            this.isExit = 1;
          }
          this.tipCount = 0;
          this.answerCount = 0;
          this.isStop = !this.isStop;
          this.shareUser = res.data.Result[0];
          // 如果有超越的好友 先显示弹窗
          if (
            this.shareUser &&
            this.shareUser != "" &&
            this.shareUser != undefined
          ) {
            this.isShareAnswerBox = true;
          } else {
            if (this.rankList.length > 0) {
              this.showOverFriendBox = true;
            } else {
              this.isShowQuestionBox = true; //显示弹窗
            }
          }
          // this.isShowQuestionBox = true; //显示弹窗
          console.log(res.data.Result[0]);
        });
    },
    closeBox() {
      this.isShareAnswerBox = false;
      if (this.rankList.length > 0) {
        this.showOverFriendBox = true;
      } else {
        this.isShowQuestionBox = true; //显示弹窗
      }
    },
    getHelpList(){
      this.helpArry=[];
      this.fly.post("/getHelpList").then(res=>{
        console.log(res.data);
        if(res.data.Result!=''){
          for(let i=0;i<res.data.Result.length;i++){
            console.log(this.helpArry);
            this.helpArry.push(res.data.Result[i]);
          }
          setTimeout(()=>{
            this.getSubject(); //这边提交
          },3000)
        }
      })
    },
    failHandel(type) {
      //回答错误
      //TODO
      // 选项型
      console.log("tishi");
      this.playAudio("static/audio/wrong.mp3");
      if (this.sType == 1) {
        if (type == "answer") {
          this.tipCount++;
        }
        this.setEnergy(this.energy - this.tipEnergy);
        wx.showToast({
          title: "金币-5",
          icon: "none",
          duration: 1000
        });
      }
      this.answerCount++;
      this.getHelpList();
    },
    noBlood() {
      //没有体力时候 触发  弹窗操作
    },
    exit() {
      this.fly
        .post("/exitSubject", {
          subjectId: this.subject.id,
          type: this.sType,
          replyCount: this.answerCount,
          promptCount: this.tipCount,
          intervalTimer: 0,
          isExit: this.isExit
        })
        .then(res => {
          this.answerCount = 0;
          this.tipCount = 0;
        });
    },
    passGame() {
      this.isPassGame = false;
      this.$router.push("/pages/entry/index");
    }
  },
  cloeTime() {
    console.log("sdsd");
  },
  onLoad(options) {
    dataStack.push({ ...this.$data });
  },
  onUnload() {
    this.exit();
    Object.assign(this.$data, dataStack.pop());
  },
  async mounted() {
    this.initAudio();
    await this.getSubject();
  },
  // onHide() {
  // },
  onShareAppMessage: function(res) {
    let x = Math.ceil(Math.random() * 7);
    return {
      title: this.shareInfo[x - 1].text,
      imageUrl: this.shareInfo[x - 1].url,
      path:
        "/pages/entry/index?userId=" +
        this.appInfo.userId +
        "&subjectId=" +
        this.subject.id,
      success: res => {
        this.fly
          .post("/updateStrength", {
            count: 30,
            type: 0
          })
          .then(res => {
            this.setEnergy(res.data.Result);
            if (res.data.Result >= this.sysConfig.maxEnergy) {
              wx.showToast({
                title: "金币已达上限",
                icon: "none"
              });
            } else {
              wx.showToast({
                title: "分享成功,金币+30",
                icon: "none"
              });
            }
          });
      }
    };
  }
};
</script>

<style lang="scss" scoped>
.wrap {
  position: relative;
  min-height: 100%;
  font-family: "Helvetica Neue", Helvetica, Arial, "PingFang SC",
    "Hiragino Sans GB", "Heiti SC", "Microsoft YaHei", "WenQuanYi Micro Hei";
  background-size: 750rpx 1206rpx;
  background-repeat: no-repeat;
  background-color: #fcda7b;
  background-image: url("");
}
// 关卡
.level-box {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 32rpx 0;
  margin-bottom: 6rpx;
  box-sizing: border-box;
  position: relative;
  img {
    width: 64rpx;
    height: 61rpx;
  }
  .current-level {
    font-size: 48rpx;
    padding: 0 6rpx 0 4rpx;
    font-weight: bold;
    color: #fcd180;
    font-family: "Helvetica Neue", Helvetica, Arial, "PingFang SC",
      "Hiragino Sans GB", "Heiti SC", "Microsoft YaHei", "WenQuanYi Micro Hei";
  }
  .energy-box {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    right: 60rpx;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    img {
      height: 56rpx;
      width: 56rpx;
      margin-right: 8rpx;
    }
  }
}
// 题目 标题
.question-title {
  width: 100%;
  padding: 24rpx 0 0 auto;
  font-size: 36rpx;
  text-align: center;
  color: #fff;
  line-height: 1;
}

.word {
  color: transparent;
  width: 628rpx;
  height: 262rpx;
  margin: 24rpx auto 45rpx;
  background: transparent;
  border: 4rpx solid #fbcdd3;
  padding: 10rpx 14rpx;
  box-sizing: border-box;
  position: relative;
  .title-box {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    align-items: center;
    justify-content: center;
    width: 608rpx;
    height: 238rpx;
    line-height: 1.5em;
    // content: attr(data-title);
    color: #c73e5f;
    font-weight: bold;
    padding: 0 70rpx;
    box-sizing: border-box;
    background: #fbcdd3;
  }
  // &:after {
  //   position: absolute;
  //   left: 50%;
  //   top: 50%;
  //   transform: translate(-50%, -50%);
  //   display: flex;
  //   align-items: center;
  //   justify-content: center;
  //   width: 608rpx;
  //   height: 238rpx;
  //   line-height: 1.5em;
  //   content: attr(data-title);
  //   color: #c73e5f;
  //   font-weight: bold;
  //   padding: 0 70rpx;
  //   box-sizing: border-box;
  //   background: #fbcdd3;
  // }
}
// 图片提示
.question-img {
  width: 660rpx;
  height: 424rpx;
  display: flex;
  margin: 38rpx auto 16rpx;
  justify-content: center;
  align-items: center;
  img {
    max-width: 660rpx;
    max-height: 424rpx;
    border: 8rpx solid #fff;
    vertical-align: top;
    border-radius: 8rpx;
    // transition: all 0.2s ease;
  }
}

// 功能操作区域
.fn-box {
  position: relative;
  display: flex;
  justify-content: center;
  margin-bottom: 6rpx;
  font-size: 10rpx;
  line-height: 50rpx;
  .fn-btn {
    position: relative;
    width: 142rpx;
    height: 52rpx;
    border-radius: .8rem;
    background-color: #f6b678;
    margin: 10rpx 8rpx 24rpx 8rpx;
    box-shadow:1rpx 1rpx 3rpx 5rpx #efa75f;
    margin-left: 16rpx;
    &:active {
      transform: scale(0.8);
    }
    &.idea-m {
      &>img {
        width: 50rpx;
        height: 52rpx;
        margin-left: 14rpx;
      }
    }
    &.skip-m {
      &>img {
        width: 50rpx;
        height: 52rpx;
        margin-left: 16rpx;
      }
    }
    &.user-m {
      &> button {
        width: 142rpx;
        height: 52rpx;
        font-size: 30rpx;
        text-align: center;
        padding: 0;
        &>img {
          width: 50rpx;
          height: 52rpx;
          margin-right:75rpx;
        }
        span {
          position:absolute;
          top:-9rpx;
          font-size:30rpx;
          left:65rpx;
        }
      }
    }
  }
  button {
    border: none;
  }
  span {
    position: absolute;
    top: 0;
    font-size:30rpx;
    color: #FFF;
  }
}
.sub-animate {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: -1;
  opacity: 0;
  img {
    width: 56rpx;
    height: 56rpx;
    margin-right: 10rpx;
  }
  font-size: 30rpx;
  font-weight: bold;
  color: #fff;
}
.flyUp {
  z-index: 5;
  animation: fly 1s ease;
  opacity: 1;
}
@keyframes fly {
  0% {
    // opacity: 1;
    transform: translateY(0);
  }
  100% {
    transform: translateY(-100rpx);
    // opacity: 0;
  }
}
.mt34 {
  margin-top: 26rpx;
}
</style>
